package com.sunky.rfidapp

import android.content.Context
import android.content.pm.PackageManager
import android.text.TextUtils
import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.sunky.db.model.ChiperEquipInfo
import com.sunky.db.model.EquipInfo
import com.sunky.db.model.EquipInfoV2
import com.sunky.db.util.DBManager
import com.sunky.db.util.addAll
import com.sunky.db.util.deleteAll
import com.sunky.db.util.getFirst
import com.sunky.rfidapp.V2.CheckEquipActivityV2
import com.sunky.rfidapp.V2.QueryInfoActivityV2
import com.sunky.rfidapp.network.NetBuilder
import com.sunky.rfidapp.network.RequestManager
import com.sunky.rfidapp.util.RFIDUtils
import com.sunky.rfidapp.util.showException
import com.sunky.rfidapp.util.showInfoDialog
import com.sunky.rfidapp.util.yes
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject

class MainActivity : BaseActivity() {

    var connected: Boolean = false

    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun initView() {
        TvConfig.setOnClickListener { openActivity(ConfigActivity::class.java) }
        TvDownload.setOnClickListener {
            if (TextUtils.isEmpty(NetBuilder.sUrl) || TextUtils.isEmpty(NetBuilder.sCode)) {
                toast("请先配置参数")
                openActivity(ConfigActivity::class.java)
                return@setOnClickListener
            }
            toast("开始下载数据")
            RequestManager.create().getEquipList("getequiplist", NetBuilder.sCode)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnNext {
                        toast("数据下载完成，开始存库")
                        showInfoDialog(it)
                    }
                    .doOnError {
                        it.printStackTrace()
                        toast("数据下载失败，请检查网络")
                        showException(it)
//                        showInfoDialog(getStackTraceString(it))
                    }
                    .observeOn(Schedulers.io())
                    .flatMap {
                        var str = it
                        Observable.create<String> {
                            DBManager.getInstance().deleteAll(equipDao)
                            DBManager.getInstance().deleteAll(chipperDao)
                            DBManager.getInstance().deleteAll(checkRecordDao)
                            //V2新增
                            DBManager.getInstance().deleteAll(equipDaoV2)
//                            parseData(str)
                            parseDataV2(str)
                            it.onNext(str)
                        }
                    }
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({
                        Log.e("数据存库完成", it)
                        toast("数据存库完成")
                    }, {
                        it.printStackTrace()
                        toast("数据存库失败")
                        showException(it)
//                        showInfoDialog(getStackTraceString(it))
                    }, {
                        toast("数据存库完成")
                    })
        }
//        TvDownload.setOnClickListener {
//            Observable.create<Any> {
//                var input = assets.open("test")
//                var bytes = ByteArray(input.available())
//                input.read(bytes)
//                JSONObject(String(bytes)).optJSONArray("EquipList")
//                        .toString().apply {
//                            var equipList = Gson().fromJson<List<EquipInfoV2>>(this, object : TypeToken<List<EquipInfoV2>>() {}.type)
//                            DBManager.getInstance().addAll(equipDaoV2, equipList)
//                        }
//                input.close()
//                it.onNext(input)
//            }.subscribeOn(Schedulers.io())
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe({},{
//                        it.printStackTrace()
//                        showException(it)
//                    })
//        }
        TvCheckEquip.setOnClickListener { openActivity(CheckEquipActivityV2::class.java) }
        TvQueryInfo.setOnClickListener { openActivity(QueryInfoActivityV2::class.java) }
    }
    private fun parseData(str: String) {
        var equipAndChip = str.split("##")
        var hasEquip: Boolean
        var hasChip: Boolean
        if (equipAndChip.size == 2) {
            hasEquip = true
            hasChip = true
        } else {
            var json = JSONObject(str)
            hasEquip = json.has("EquipList")
            hasChip = json.has("CipherList")
        }
//        hasEquip = false;
        if (hasEquip) {
            JSONObject(equipAndChip[0]).optJSONArray("EquipList")
                    .toString().apply {
                        var equipList = Gson().fromJson<List<EquipInfo>>(this, object : TypeToken<List<EquipInfo>>() {}.type)
                        DBManager.getInstance().addAll(equipDao, equipList)
                    }
        }

        if (hasChip) {
            var chipStr = if (equipAndChip.size == 1) equipAndChip[0] else equipAndChip[1]
            JSONObject(chipStr).optJSONArray("CipherList")
                    .toString().apply {
                        var cipherList = Gson().fromJson<List<ChiperEquipInfo>>(this, object : TypeToken<List<ChiperEquipInfo>>() {}.type)
                        DBManager.getInstance().addAll(chipperDao, cipherList)
                    }
        }
    }

    private fun parseDataV2(str: String) {
            JSONObject(str).optJSONArray("EquipList")
                    .toString().apply {
                        var equipList = Gson().fromJson<List<EquipInfoV2>>(this, object : TypeToken<List<EquipInfoV2>>() {}.type)
                        DBManager.getInstance().addAll(equipDaoV2, equipList)
                    }
    }

    override fun initData() {
        connected = RFIDUtils.connect()
        DBManager.getInstance().getFirst(configDao)?.apply {
            NetBuilder.sUrl = this.serverAddr
            NetBuilder.sCode = this.deviceNo
            NetBuilder.getInstance().refreshRetrofit()
            RequestManager.refreshService()
        }
        tvVersion.text = getVersionName(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        connected.yes {
            RFIDUtils.disconnect()
        }
    }

    fun getVersionName(context: Context): String {
        return try {
            val packageManager = context.packageManager
            val packageInfo = packageManager.getPackageInfo(context.packageName, 0)
            packageInfo.versionName
        } catch (var3: PackageManager.NameNotFoundException) {
            var3.printStackTrace()
            ""
        }

    }
}
